import colorsys

import pydot
import matplotlib
import matplotlib.pyplot as plt
import io

matplotlib.rcParams['font.family'] = 'sans-serif'
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
def render_one(code,title,dict=None,footer=None,delay=2):
    fig = plt.figure('数据结构与算法(Python)-课程实验', [10, 6])
    fig.clear()
    ax = fig.gca()
    plt.axis('off')
    # render title
    plt.title(f'{title}',fontsize=18,color='b',pad=10,y=5)
    # render 内存栈
    font_size = 12
    var_label_len = 10
    line_height,line_count = 2.5,5
    col2_left = 500
    plt.text(0.0, - font_size * line_height * (line_count+1), "内存变量", size=font_size, color='r')

    i = 0
    for key in dict:
        if i<line_count:
            plt.text(0.0, - font_size * line_height * (line_count-i),
                     '%s:' % key.ljust(var_label_len), size=font_size, color='k')
            plt.text(font_size * (var_label_len+1), - font_size * line_height * (line_count-i),
                     dict[key], size=font_size, color='b')
        else:
            plt.text(col2_left, - font_size * line_height * (2 * line_count - i),
                     '%s:' % key.ljust(var_label_len), size=font_size, color='k')
            plt.text(col2_left + font_size * (var_label_len + 1), - font_size * line_height * (2* line_count - i),
                     dict[key], size=font_size, color='b')
        i += 1

    #render footer
    if footer and len(footer)>0:
        plt.text(400,360,footer,color='k')
    else:
        plt.text(380, 360, '版权所有 by 熊松泉', color='#ccc')
    try:
        graphs = pydot.graph_from_dot_data(code)
        for graph in graphs:
            bytes = graph.create_png()
            byte_io = io.BytesIO(bytes)
            ax.imshow(plt.imread(byte_io))
            fig.show()

            plt.pause(delay)
    except Exception as e:
        print(e)

def render(tup,delay=10):
    for it in tup:
        code,title,dict = it[0],it[1],it[2]
        render_one(code,title,dict)

    it = tup[len(tup)-1]
    code, title, dict = it[0], it[1], it[2]
    for i in range(delay,-1,-1):
        footer = f'{i}秒后关闭'
        render_one(code,title,dict,footer,1)


